var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var app = express();

var pool = mysql.createPool({
	host: 'localhost',
	port: 3306,
	database: 'test',
	user : 'root',
	password: '123456'
});


app.all('/index.html/:id(\\d+)', function(req, res, next){

	pool.getConnection(function(err, connection){
		if(err)
			res.send('与MYSQL数据库建立连接失败');
		else{
			var str;
			connection.query('select count(1) count from mytable where id=?',
			[req.params.id],
			function(err, result){
				if(err){
					res.send('在服务器端MYSQL数据库中查询数据失败。');
					connection.release();
				}
				else{
					console.log(result)
					connection.release();
					if(result[0].count > 0)
						next();
					else
						res.send('您没有操作数据库的权限');
				}
			});
		}
	});

});

app.get('/index.html/:id(\\d+)', function(req, res){
	res.sendfile(__dirname + '/index5.html');
});

app.post('/index.html/:id(\\d+)', function(req, res){
	req.on("data", function(data){
		var obj = JSON.parse(data.toString());
		pool.getConnection(function(err, connection){
			if(err)
				res.send('与MYSQL数据库建立连接失败');
			else{
				var str;
				connection.query('update mytable set name=?,sex=? where id=?',
				[obj.name, obj.sex, req.params.id],
				function(err, result){
					if(err)
						str = '在服务器端MYSQL数据库中更新数据失败。';
					else
						str = '在服务器端MYSQL数据库中更新数据成功。';
						connection.release();
						res.send(str);
				});
			}
		});	
	});
});

app.listen(1337, 'localhost');